﻿using FastMvc.Crud;
using FastMvc.Repositories;
using JQ.SAAS.DTO.SysMenus;
using JQ.SAAS.Entity;
using JQ.SAAS.IService;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JQ.SAAS.Service
{
    public class SysMenusService : CrudService<sys_menu, SysMenusDto, string, SysMenusListRequestDto, SysMenusCreateDto, SysMenusUpdateDto>, ISysMenusService
    {
        public SysMenusService(IRepository<sys_menu> repository)
            : base(repository)
        { }

        public async Task<List<SysMenusDto>> GetTreeList()
        {
            var allTree = await this.Repository.GetAllAsync();

            // 加载页面菜单列表
            List<SysMenusDto> menuList = allTree.Where(t => t.iType == 0).Select(t => MapToDto(t).Result).ToList();

            // 为菜单列表，加载操作列表
            menuList.ForEach(menu => 
            {
                menu.Childs = allTree.Where(t => t.iType == 1 && t.ParentId == menu.sId).Select(t=>MapToDto(t).Result).ToList();
            });

            return await Task.FromResult(menuList);
        }

        public override async Task<SysMenusDto> CreateNew(SysMenusCreateDto createDto)
        {
            // 新建时，增加数据验证
            if (createDto.iType == 1)
            {
                var parent = await Repository.FirstOrDefaultAsync(t => t.iType == 0 && t.IEnabled == 0 && t.sId == createDto.ParentId);

                if (parent == null)
                {
                    throw new FastMvc.Exceptions.ApiException("未找到操作菜单对应的页面菜单！");
                }
            }

            return await base.CreateNew(createDto);
        }

        protected override ISugarQueryable<sys_menu> SetSugarQueryable(ISugarQueryable<sys_menu> query, SysMenusListRequestDto requestDto = null)
        {
            if (requestDto != null)
            {
                return query.WhereIF(!string.IsNullOrEmpty(requestDto.MenuName), t => t.sName.Contains(requestDto.MenuName))
                        .WhereIF(requestDto.MenuType.HasValue, t => t.iType == requestDto.MenuType);
            }
            return query;
        }
    }
}
